const { app, BrowserWindow,globalShortcut,dialog  } = require('electron');
const path = require('path');
const shell = require('electron').shell
const fs = require('fs')
// const { autoUpdater } = require('electron-updater');
if (require('electron-squirrel-startup')) {
  app.quit();
}

const createWindow = () => {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      nodeIntegration: false,
      contextIsolation: true,
    },
    autoHideMenuBar: true,
  });


  mainWindow.loadURL('http://39.99.141.254:80/')  //正式地址
  //mainWindow.loadURL('http://39.99.141.254:30003/')  //测试地址  
  //mainWindow.loadURL('http://localhost:3001/')    //本地

    // 注册 F5 快捷键刷新页面
    globalShortcut.register('F5', () => {
      mainWindow.reload()
    })
  
    // 注册 F10 快捷键打开开发者工具
    globalShortcut.register('F10', () => {
      mainWindow.webContents.openDevTools()
    })

  mainWindow.webContents.on('before-input-event', (event, input) => {
    if (input.control && input.key.toLowerCase() === 'r') {
      mainWindow.reload()
    }
    if (input.control && input.shift && input.key.toLowerCase() === 'i') {
      mainWindow.webContents.openDevTools()
    }
  })
  
  mainWindow.webContents.session.on('will-download', (event, item) => {
    let fileName = item.getFilename()
    let fileExtension = path.extname(fileName)
    let baseName = path.basename(fileName, fileExtension)
    let savePath = path.join(app.getPath('downloads'), fileName)
  
    // if file already exists, add a number to the filename
    let counter = 1;
    while (fs.existsSync(savePath)) {
      let newFileName = `${baseName}_${counter}${fileExtension}`
      savePath = path.join(app.getPath('downloads'), newFileName)
      fileName = newFileName
      counter++;
    }
    
    item.setSavePath(savePath)
    
    item.once('done', async (event, state) => {
      if (state === 'completed') {
        dialog.showMessageBox({
          title: '文件下载',
          message: `文件 ${fileName} 已经下载成功 ${app.getPath('downloads')}`,
        })
  
        try {
          await shell.openPath(savePath)
        } catch (err) {
          dialog.showErrorBox('File Open Failed', `File ${fileName} could not be opened. ${err.message}`)
        }
      } else {
        dialog.showErrorBox('File Download Failed', `File ${fileName} download failed.`)
      }
    })
  })
  


};






app.on('will-quit', () => {
  //注销所有全局快捷键
  globalShortcut.unregisterAll()
})

app.on('ready', function()  {
  //autoUpdater.checkForUpdatesAndNotify();
  createWindow();
});

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow();
  }
});



